package web.suzy.oj.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import web.suzy.oj.annotation.Access;
import web.suzy.oj.annotation.AccessEnum;
import web.suzy.oj.utils.ServiceContextUtils;
import web.suzy.oj.validator.AccessValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * YangSuzy 软件工作室
 * 类名: AccessInterceptor
 * 描述: 访问功能拦截器
 * 功能: 拦截需要访问权限的功能，判断是否开启该功能的访问
 *
 * @author YangSuzy
 * Date: 2022/12/9 16:31
 */
@Component
public class AccessInterceptor implements HandlerInterceptor {
    @Autowired
    private AccessValidator accessValidator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = HandlerMethod.class.cast(handler);
            //获取方法的访问注解
            Access access = ServiceContextUtils.getAnnotation(handlerMethod.getMethod(), handlerMethod.getBeanType(), Access.class);
            //注解为空时跳过
            if (access == null || access.value().length == 0) {
                return true;
            }
            //验证该注解对应的功能是否开启，未开启时抛出全局异常
            for (AccessEnum value : access.value()) {
                accessValidator.validateAccess(value);
            }
            return true;
        } else {
            //静态资源的请求不处理
            return handler instanceof ResourceHttpRequestHandler;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
